import React, {Component, PureComponent} from "react";
import styles from './index.module.less';
import ActionBar from "./ActionBar";
import {Button, Form, Pagination, Spin, Modal, Tag, Result} from "antd";
import { jsonParse, myFormatTime, dateStr2Timestamp, getRandomKey} from "jh-utils";
import ModalComp from "../ModalItem/ModalComp";
import InputComp from "../InputComp";
import BaseComp from "../Base/BaseComp";
import { jhError, jhMessage } from "../../utils/base";

import {forEach, isArray, isEmpty, omit, isFunction, map, isObject, isNumber, pick, cloneDeep} from "lodash-es";
import SheetExcel from "./SheetExcel";

import FolderModal from "./folderModal"

const tagStyle = {
    color: '#333',
    marginBottom: 4,
    // borderRadius: 0,
};
const tagSpanStyle = {
    // maxWidth: 150,
    display: 'inline-block',
    overflow: 'hidden',
    float: 'left',
    textOverflow: 'ellipsis',
};

/**
 * 表格预览
 */
export default class SheetExcelComp extends BaseComp {
    formRef = React.createRef();
    actionBarRef;
    snFormRef;
    previewFields = {};

    constructor(props) {
        super(props);
        const {isPreview, reportCode, reportParameters} = props;
        this.state = {
            reportCode: reportCode,
            loading:false,
            searchFormConf: isPreview ? reportParameters : [], // 表单配置
            docChecked:false, // 是否可协同
        };
        window.appins = this;
    }

    componentDidMount() {
        // this.initData(true).then();
    }

    setLoading(loading = false, cb){
        this.setState({loading},()=>{
            isFunction(cb) && cb();
        })
    }

    async initData(isMount = false) {
        let {searchFormConf} = this.state;
        if (true !== this.props.isPreview) {
            await this.fetchSheetFormConf();
        } else {
            if (isMount && isEmpty(searchFormConf)) {
                await this.fetchSheet();
            }else{
                this.setState({loading:false});
            }
        }
    }

    fetchSheetFormConf() {
        const {reportCode} = this.state;
        this.reqGet(`/api/bi/designer/load_report`,{reportCode}).then(rsp => {
            if (rsp && 200 === rsp.status) {
                const {data = {}} = rsp;
                const {design = '',docChecked} = data;
                const reportConf = jsonParse(design);
                const {reportProperty = {}} = reportConf;
                let {reportParameters = []} = reportProperty;

                // reportParameters = reportParameters.filter(p => p.parameterType == 0); //general
                this.setState({searchFormConf: reportParameters, docChecked}, () => {
                    if (isEmpty(reportParameters)) {
                        this.fetchSheet();
                    }else{
                        this.setState({loading:false});
                    }
                });
            }else{
                this.setState({loading:false});
            }
        })
    }

    // 查询预览, 直接 导入 sheetExcel
    fetchSheet() {

        this.setState({loading:true},()=>{
            if (this.actionBarRef && this.actionBarRef.hdlExport) {
                this.actionBarRef.hdlExport('excel', (api) => {
                    let { docChecked = false } = this.state;
                    this.reqGet(`/api/bi/excel/team_doc_export?docChecked=${docChecked}`).then(rsp => {
                        if (rsp && rsp.status == 200) {
                            let savePath = `/api/doc/file?filePath=${rsp.data && rsp.data.savePath || ""}`;
                            this.setState({excelApis:{...rsp.data,savePath}},()=>{
                                this.excelToLucky();
                            });
                        }else{
                            this.setState({loading:false});
                        }
                    });
                })();
            }else{
                this.setState({loading:false});
            }
        });

    }
    get contentWindow(){
        if (window) {
            return window
        }
        return null;
    }
    /**
     *  导入 Excel
     */
    excelToLucky() {
        let previewIframe = this.contentWindow;
        if (previewIframe) {
            console.log("previewIframe:", previewIframe);

            let LuckyExcel = previewIframe.LuckyExcel;
            let { excelApis } = this.state;
            if (!isEmpty(excelApis) && LuckyExcel) {
                LuckyExcel.transformExcelToLuckyByUrl(`${excelApis.savePath}`, excelApis.fileName, (exportJson, luckysheetfile) => {
                    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
                        jhError({title: 'Failed to read the content of the excel file'});
                        return;
                    }
                    if (previewIframe.luckysheet && previewIframe.luckysheet.destroy) {
                        previewIframe.luckysheet.destroy();
                    }
                    // console.log("------------exportJson",exportJson);
                    previewIframe.luckysheet.create({
                        container: previewIframe.COMP_ID, //luckysheet is the container id
                        showinfobar: false,
                        showtoolbar: false,
                        fullscreenmode: false,
                        lang: this.getLocale() !== 'en-US' ? 'zh' : 'en',
                        allowEdit: this.props.isPreview ? false : true,
                        data: exportJson.sheets,
                        title: exportJson.info && exportJson.info.name,
                        userInfo: exportJson.info &&  exportJson.info.creator
                    });

                    this.setState({loading:false, isError: false});
                    // 删除
                    this.deleteExcel();
                }, (error)=>{
                    console.log("err:", error);
                    this.setState({loading:false, isError: true});
                })
            }else {
                this.setState({loading:false});
            }
        }
    }

    /**
     * 导入 excel后 删除 服务器文件
     * */
    deleteExcel(){
        setTimeout(()=>{
            let { excelApis } = this.state;

            if(excelApis && excelApis.savePath){
                let savePath = excelApis.savePath.split('=');
                let uid =  savePath && savePath[1] || 0
                this.jsonPost(`/api/bi/excel/del_temp_excel?uid=${uid}`).then(res=>{

                })
            }
        },50);
    }


    // 获取参数
    getSearchParams() {
        const formRef = this.formRef || {};
        if(formRef.current && formRef.current.validateFields){
            return formRef.current.validateFields().then(values => {
                return this.getSearchData(values);
            }).catch(err => {
                return false;
            })

        }else {
            return new Promise(resolve => {
                let searchParams = this.getSearchData();
                resolve(searchParams);
            })
        }
    }

    getSearchData(values = {}){
        let {searchFormConf} = this.state;
        // 将隐藏的字段附上，用于查询条件
        let newValues = {};
        forEach(searchFormConf, sc => {
            if (sc.defaultValue && sc.hideParams) {
                newValues[sc.name] = sc.defaultValue
            }
        });
        let searchParams = {
            ...values,
            ...newValues
        };
        // 时间是否包含全天
        let isContainDay = false;
        forEach(searchFormConf, sf => {
            if (sf.isContainDay && sf.isToday) {
                isContainDay = true;
            }
        });
        if (searchParams.date && isContainDay) {
            let nDate = myFormatTime(searchParams.date, 'YYYY-MM-DD');
            if (nDate) {
                nDate = nDate + " 23:59:59";
                searchParams.date = [searchParams.date, dateStr2Timestamp(nDate)]
            }
        }
        let previewFields = [];
        let newParams = cloneDeep(searchParams);
        forEach(searchFormConf, sf => {
            if(newParams[sf.name]){
                let text = newParams[sf.name];
                if(sf.componentType === "CALENDAR"){
                    if(!sf.range){
                        text = myFormatTime(text);
                    }else if(isArray(text)) {
                        text[0] = text[0] ? myFormatTime(text[0]): null;
                        text[1] = text[1] ? myFormatTime(text[1]): null;
                    }
                }else if(isObject(text) && !isArray(text)){
                    text = text.name || text.code;
                }
                let newSf = {...sf, text};
                previewFields.push(newSf)
            }
        });
        this.previewFields = previewFields;
        this.setState({randomKey: getRandomKey()});

        return searchParams;
    }

    /**
     *
     * 保存为我的文档
     * */
    saveForSynDoc(){
        // console.log('this.snFormRef:',this.snFormRef);
        this.setState({snVisible:true},()=>{
            if(this.snFormRef && this.snFormRef.setFieldsValue){
                let { reportCode } = this.state;
                this.snFormRef.setFieldsValue({
                    name: reportCode || "",
                });
            }
        });
    }

    saveOk(){
        let contentWindow = this.contentWindow;
        console.log('contentWindow',contentWindow.luckysheet);
        if(contentWindow && contentWindow.luckysheet){
            let sheet = contentWindow.luckysheet && contentWindow.luckysheet.getluckysheetfile() || [];
            let celldata = contentWindow.luckysheet.getGridData(contentWindow.luckysheet.flowdata());
            if(!isEmpty(sheet) && isArray(sheet) && sheet[0]) {
                sheet = sheet[0];
                let row = sheet.visibledatarow && sheet.visibledatarow.length;
                let column = sheet.visibledatacolumn && sheet.visibledatacolumn.length;
                let infoJson = {row, column, ...omit(sheet,['data',"celldata","visibledatacolumn","visibledatarow"])};
                let docName = "";
                if(this.snFormRef && this.snFormRef.getFieldValue){
                    docName = this.snFormRef.getFieldValue("name");
                }
                if(!docName){
                    jhMessage.warn(this.myFormatMessage('doc.name.no.found'));
                    return false;
                }
                let { folder } = this.state;
                let ajaxData  = {
                    infoJson: JSON.stringify(infoJson), // 表格初始化配置数据
                    cellDataJson:JSON.stringify(celldata),
                    docName,
                    managerId:folder.id || 0
                };
                this.jsonPost('/api/bi/team_doc/save_document ',ajaxData).then(res => {
                    if(res && res.status == 200){
                        jhMessage.success(this.formatMsgByCn('操作成功'));
                        this.setState({snVisible:false});
                    }
                })

            }
        }
    }


    /**
     * 重置
     * */
    handleReset(){
        if(this.formRef && this.formRef.current){
            this.formRef.current.resetFields();
        }
    }

    focus(){
        this.setState({folderVisible: true})
    }

    hdlOk(node = {}){
        this.setState({folder: node});
        if(this.snFormRef && this.snFormRef.setFieldsValue){
            this.snFormRef.setFieldsValue({
                folder: node.name || ""
            })
        }
    }

    hdlCancel(){
        this.setState({folderVisible: false})
    }

    mainRender() {
        const {reportCode, searchFormConf, loading, docChecked, snVisible = false, isError} = this.state;
        let {repDefaultValue, paramConfs, appInfo} = this.props;
        let layout = {
            labelCol: {span: 9},
            wrapperCol: {span: 15},
        };

        let javaType = appInfo && appInfo.javaType;
        // 过滤 搜索条件
        let newFormConf = [];
        forEach(searchFormConf, sc => {
            let newSc = {...sc};
            let componentValue = newSc.componentValue;
            if (!isEmpty(repDefaultValue) && componentValue && javaType && componentValue.javaType === javaType) {
                newSc.defaultValue = pick(repDefaultValue, ['id', 'code', 'name']);
            }
            if (!isEmpty(paramConfs) && !isEmpty(repDefaultValue)) {
                forEach(paramConfs, item => {
                    if (item && item.fieldName && item.paramName && newSc.name === item.paramName && repDefaultValue.hasOwnProperty(item.fieldName)) {
                        newSc.defaultValue = repDefaultValue[item.fieldName];
                    }
                })
            }
            if (!(sc.defaultValue && sc.hideParams)) {
                newFormConf.push(newSc)
            }
        });
        console.log('newFormConf:', newFormConf);
        // 替换搜索参数值


        return <div className={styles.sheetWrap}>
            {/*<input type="file" onChange={this.fileChange.bind(this)}/>*/}
            <Form ref={this.formRef}
                  onFinish={(values) => this.fetchSheet(values)}
                  {...layout}
            >

                <ActionBar reportCode={reportCode}
                           searchFormConf={newFormConf}
                           fetchSheet={this.fetchSheet.bind(this)}
                           handleReset={this.handleReset.bind(this)}
                           getSearchParams={this.getSearchParams.bind(this)}
                           onRef={ref => this.actionBarRef = ref}
                           loadingReview={loading}
                           isPreview={this.props.isPreview}
                           docChecked={docChecked}
                           saveForSynDoc={this.saveForSynDoc.bind(this)}
                />
            </Form>
            <div style={{padding: '10px 20px 0 20px'}}>
                {
                    map(this.previewFields, (v, k) => {
                        let pre = '';

                        pre = v.label ? `${v.label}：  ${v.text}` : (v.text || '');
                        return (
                            <Tag key={k} style={tagStyle}
                                 title={`${pre}`}
                                 closable={false}
                                 color={'blue'}>
                                <span style={tagSpanStyle}>{pre}</span>
                            </Tag>
                        );
                    })
                }
            </div>

            <div className={styles.sheetContent}>
                <Spin spinning={loading} style={{width: '100%'}}>
                    <SheetExcel
                        appins={this}
                    />
                    {
                        !loading && isError === true && <div className={styles.loadErr}>
                            <Result
                                status={'warning'}
                                title={this.myFormatMessage('doc-load-err')}
                                extra={<Button type={"primary"}
                                               onClick={this.fetchSheet.bind(this)}>
                                    {this.formatMsgByCn('重试')}
                                </Button>}
                            />
                        </div>
                    }
                </Spin>

            </div>

            <ModalComp
                title={this.formatMsgByCn("保存为我的文档")}
                visible={snVisible}
                wrapClassName={'insertQx'}
                mask={false}
                width={350}
                onOk={this.saveOk.bind(this)}
                destoryOnclose={true}
                onCancel={()=>{
                    this.setState({snVisible:false})
                }}
            >
                <Form
                    component={'div'}
                    ref={(ref)=>{this.snFormRef = ref}}
                >
                    <InputComp
                        fieldName={'name'}
                        compLabel={this.formatMsgByCn('文档名称')}
                    />
                    <InputComp
                        fieldName={'folder'}
                        onClick={this.focus.bind(this)}
                        onChange={(values)=>{
                            this.snFormRef.setFieldsValue({
                                folder: ""
                            });
                            this.setState({folder: {}});
                        }}
                        compLabel={this.formatMsgByCn('选择目录')}
                    />
                </Form>
            </ModalComp>
            {
                this.state.folderVisible && <FolderModal visible={this.state.folderVisible} hdlCancel={this.hdlCancel.bind(this)} hdlOk={this.hdlOk.bind(this)}/>
            }
        </div>
    }
}
